import React, { Component } from 'react'
import { StyleSheet, View, Platform, StatusBar, Animated } from 'react-native'

import SearchBox from '../component/SearchBox'
import SearchView from '../component/SearchView'
import { NavigationActions, px2dp } from '../utils'
import realm from '../utils/realm'

const isIOS = Platform.OS == 'ios'
const headH = px2dp(isIOS ? 120 : 100)

class Search extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: [],
    }
  }
  static navigationOptions = {
    header: null,
  }
  onSearch = keywords => {
    const { onSearch } = this.props
    onSearch(keywords)
    // 保存历史记录
    const obj = realm.objects('Search').filtered(`value = "${keywords}"`)

    try {
      if (obj.length < 1) {
        realm.write(() => {
          realm.create('Search', {
            id: String(new Date().getTime()),
            value: keywords,
          })
        })
      }
    } catch (e) {}
  }
  loadData = () => {
    const data = realm.objects('Search')
    this.setState({ data })
  }
  onTrash = () => {
    const data = realm.objects('Search')
    try {
      realm.write(() => {
        realm.delete(data)
        this.loadData()
      })
    } catch (e) {}
  }
  onHistorySearch = keywords => {
    this.props.onSearch(keywords)
  }
  componentDidMount = () => {
    this.loadData()
    setTimeout(() => {
      this.refs.searchBox.focus()
    }, 50)
  }

  renderFixHeader() {
    const { onCancel, onSearch } = this.props
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <SearchBox
            ref="searchBox"
            placeholder="搜索商品"
            cancelTitle="取消"
            titleCancelColor="#999"
            backgroundColor="transparent"
            inputHeight={28}
            onSearch={keywords => this.onSearch(keywords)}
            onCancel={() => onCancel()}
          />
        </View>
        <SearchView
          data={this.state.data}
          onTrash={this.onTrash}
          onSearch={this.onHistorySearch}
        />
      </View>
    )
  }

  render() {
    return <View style={styles.container}>{this.renderFixHeader()}</View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  header: {
    backgroundColor: 'white',
    paddingTop: px2dp(isIOS ? 30 : 10),
    paddingHorizontal: 16,
    marginTop: -10,
  },
})

export default Search
